<template>
  <container>
    <!-- 类似于img标签 -->
    <!-- <sprite :texture='mapImg'></sprite> -->
    <Map></Map>
    <Plane :x='planeInfo.x' :y='planeInfo.y'></Plane>
    <EnermyPlane v-for="(enermy,index) in enermyPlanes" :key="index" :x="enermy.x" :y="enermy.y"></EnermyPlane>
    <!-- <EnermyPlane></EnermyPlane> -->

    <Bullets v-for="(bullet,index) in bullets" :key="index" :x="bullet.x" :y="bullet.y"></Bullets>
  </container>
</template>

<script>
import Map from '@/components/Map.vue'
import EnermyPlane from '@/components/EnermyPlane.vue'
import { useEnermyPlane } from '@/components/EnermyPlane.vue'
import Plane from '@/components/Plane.vue'
import { usePlane } from '@/components/Plane.vue'
import { game } from '@/game/index.js'
import { onMounted, onUnmounted } from 'vue'
import { hitTestObject } from '@/utils/index.js'
import Bullets from '@/components/Bullets.vue'
import { useBullets } from '@/components/Bullets.vue'

export default {
  components: {
    Map,
    Plane,
    EnermyPlane,
    Bullets
  },
  setup(props, { emit }) {
    // 构建敌军数据
    const { enermyPlanes } = useEnermyPlane()

    // 子弹
    const { bullets, addBullet } = useBullets()

    // 发射子弹
    const { planeInfo } = usePlane({
      onAttack(position) {
        addBullet(position)
      }
    })

    // 战斗逻辑
    useFighting(bullets, planeInfo, enermyPlanes, emit)

    return {
      planeInfo,
      enermyPlanes,
      bullets
    }
  }
}

function useFighting(bullets, planeInfo, enermyPlanes, emit) {
  // 检测是否碰撞
  const handleTicker = () => {
    // 碰撞检测
    enermyPlanes.forEach(enermy => {
      if (hitTestObject(planeInfo, enermy)) {
        // game over
        emit('change-page', 'EndPage')
      }
    })
    // 遍历敌军和我方子弹
    enermyPlanes.forEach((enermy, enermyIndex) => {
      bullets.forEach((bullet, bulletIndex) => {
        if (hitTestObject(enermy, bullet)) {
          console.log('hiy')
          enermyPlanes.splice(enermyIndex, 1)
          bullets.splice(bulletIndex, 1)
        }
      })
    })
  }

  const move = () => {
    enermyPlanes.forEach(enermy => {
      enermy.y++
    })
  }

  onMounted(() => {
    game.ticker.add(handleTicker)
    game.ticker.add(move)
  })

  onUnmounted(() => {
    game.ticker.remove(handleTicker)
    game.ticker.remove(move)
  })
}
</script>
